package com.umanji.usedmarket;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.umanji.category.domain.Categories;
import com.umanji.category.service.CategoryService;
import com.umanji.security.domain.Users;
import com.umanji.security.service.UserService;
import com.umanji.usedmarket.domain.UsedProducts;
import com.umanji.usedmarket.service.UsedProductService;
import com.umanji.user.UserController;
import com.umanji.user.domain.Members;
import com.umanji.user.service.MemberService;

/**
 * Handles requests for the application welcome page.
 */
@Controller
@RequestMapping(value = "/usedmarket")
public class UsedmarketController {

	private Logger logger = org.slf4j.LoggerFactory
			.getLogger(UsedmarketController.class);

	private Validator validator = Validation.buildDefaultValidatorFactory()
			.getValidator();

	@Autowired
	public UsedmarketController(Validator validator) {
		this.validator = validator;
	}

	@Autowired
	private UsedProductService usedProductService;

	@Autowired
	private MemberService umanjiUserService;

	@Autowired
	private UserService securityUserService;

	@RequestMapping(value = "/createTo", method = RequestMethod.GET)
	public String createFormGo(final HttpServletRequest request, ModelMap model) {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		if (principal instanceof UserDetails) {
			return "redirect:create";
		} else {
			return "redirect:../user/needLog";
		}
	}

	@RequestMapping(value = "/creater", method = RequestMethod.GET)
	public ModelMap createFormGoTo(final HttpServletRequest request,
			ModelMap model) {
		return model;
	}

	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public ModelMap createForm(final HttpServletRequest request, ModelMap model) {
		logger.info("create used product form!");
		Users user = new Users();
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		if (principal instanceof UserDetails) {

			logger
					.info(":::::::::::::::::::::::::::::::::::::::: found user ::::::::::::::::::");
			user = securityUserService.findByUsername(((UserDetails) principal)
					.getUsername());
		}
		UsedProducts usedProduct = new UsedProducts();
		usedProduct.setMember(user.getMember());
		usedProduct.setUser_name(user.getUsername());
		model.addObject("umj_used_product", usedProduct);
		model.addObject("umjj_user", user);

		return model;

	}

	@RequestMapping(value = "/term/create", method = RequestMethod.GET)
	public ModelMap terms(ModelMap model) {
		return model;
	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(
			@ModelAttribute("umj_used_product") UsedProducts umanji_usedproduct,
			BindingResult result, HttpServletRequest request) {
		logger.info("register user!");

		request.getRealPath("/");
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				System.err.println("Error: " + error.getCode() + " - "
						+ error.getDefaultMessage());
			}
			return "usedmarket/create";
		}

		/*
		 * [출처] Spring2.5 MultipartResolver를 이용한 멀티업로드 구현...|작성자 쪼렙
		 * 
		 * String savePath = context.getServletContext().getRealPath("/upload");
		 * 
		 * List fileList = multiUpload.getFile(); Iterator it =
		 * fileList.iterator(); while(it.hasNext()){ MultipartFile multiFile =
		 * (MultipartFile)it.next(); if(multiFile.getSize() > 0){
		 * multiFile.transferTo(new File(savePath + "/" +
		 * multiFile.getOriginalFilename())); } }
		 * 
		 * 
		 * if (!productImageFile.isEmpty()) { try { byte[] bytes =
		 * productImageFile.getBytes();
		 * System.err.println("-------------------------------------------");
		 * System.err.println("Test file uploaded : ");
		 * System.err.println("-------------------------------------------"); }
		 * catch (IOException e) { // TODO Auto-generated catch block
		 * e.printStackTrace(); } // store the bytes somewhere return
		 * "redirect:uploadSuccess"; }
		 */

		// Some type of file processing...
		System.err.println("-------------------------------------------");
		System.err.println("Test upload: " + umanji_usedproduct.getContent());
		System.err.println("Test upload: "
				+ umanji_usedproduct.getFileData().getOriginalFilename());
		try {
			String rootPath = WebUtils.getRealPath(request.getSession()
					.getServletContext(), "upload");
			umanji_usedproduct.setProductImage(umanji_usedproduct
					.getSavedFileName(rootPath, umanji_usedproduct
							.getFileData(), "usedProduct"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.err.println("-------------------------------------------");

		for (ConstraintViolation<UsedProducts> constraint : validator
				.validate(umanji_usedproduct)) {
			result.rejectValue(constraint.getPropertyPath().toString(), "",
					constraint.getMessage());
		}
		if (result.hasErrors())
			return "usedmarket/create";

		Users user = new Users();
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		if (principal instanceof UserDetails) {

			logger
					.info(":::::::::::::::::::::::::::::::::::::::: found user ::::::::::::::::::");
			user = securityUserService.findByUsername(((UserDetails) principal)
					.getUsername());
		}

		umanji_usedproduct.setMember(user.getMember());
		usedProductService.persist(umanji_usedproduct);
		return "redirect:/umj/usedmarket/create";
	}

	/**
	 * 중고물품 검색 기능
	 * 
	 * @param search
	 * @return
	 */
	@RequestMapping(value = "/usedFind", method = RequestMethod.GET)
	public ModelMap usedFind(@RequestParam("search") String search,
			final HttpServletRequest request, ModelMap model) {

		System.err.println("###################find her!" + search);

		List<?> used = usedProductService.find(search);

		model.addObject("umj_used_product", used);

		return model;

	}
	
	//중고물품 상세보기 팝업처리
	@RequestMapping(value = "/showDetail", method = RequestMethod.GET)
	public ModelAndView showDetail(@RequestParam("id") Long id, ModelAndView mav){
		UsedProducts used= usedProductService.find(id);
		mav.setViewName("usedmarket/retrieve");
		mav.addObject("used_showDetail",used);		
		return mav;
	}
	
}
